package com.atguigu.acl.service.impl;

import com.atguigu.acl.dto.PermissionNode;
import com.atguigu.acl.entity.Permission;
import com.atguigu.acl.mapper.PermissionMapper;
import com.atguigu.acl.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author smday
 * @since 2020-08-10
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    public int create(Permission permission) {
        return baseMapper.insert(permission);
    }

    @Override
    public int update(Long id, Permission permission) {
        permission.setId(id);
        return baseMapper.updateById(permission);
    }

    @Override
    public int delete(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public List<PermissionNode> treeList() {
        //查询所有的权限列表
        List<Permission> permissionList = baseMapper.selectList(null);
        return  permissionList.stream().filter(permission -> permission.getPid().equals(0L))
                .map(permission -> convert(permission, permissionList))
                .collect(Collectors.toList());
    }

    /**
     * permission --> permissionNode (children)
     */
    private PermissionNode convert(Permission permission, List<Permission> permissionList) {

        PermissionNode permissionNode = new PermissionNode();
        BeanUtils.copyProperties(permission,permissionNode);

        List<PermissionNode> children = permissionList.stream().filter(sub -> sub.getPid().equals(permission.getId()))
                .map(sub -> convert(sub, permissionList))
                .collect(Collectors.toList());
        permissionNode.setChildren(children);
        return permissionNode;

    }

    @Override
    public List<Permission> list() {
        return baseMapper.selectList(null);
    }
}
